package com.cvmars.jianyou.module.activity;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.cvmars.jianyou.R;
import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.config.MyConfig;
import com.cvmars.jianyou.model.UserCoustomModel;
import com.cvmars.jianyou.model.UserModel;
import com.cvmars.jianyou.module.adapter.VectorTagsAdapter;
import com.cvmars.jianyou.module.adapter.XiangQingAdapter;
import com.cvmars.jianyou.module.base.BaseActivity;
import com.cvmars.jianyou.ui.pulltorefresh.PulltoRefreshRecyclerView;
import com.kd.easybarrage.Barrage;
import com.kd.easybarrage.BarrageView;
import com.moxun.tagcloudlib.view.TagCloudView;
import com.orhanobut.hawk.Hawk;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class XiangQingDaTingActivity extends BaseActivity {


    int mCurPager = 1;

    XiangQingAdapter homeAdapter;
    List<UserModel> list = new ArrayList<>();
    int mCurPage = 1;
    @BindView(R.id.txt_xiangqing)
    Button txtXiangqing;

    public MediaPlayer mediaPlayer;
    boolean isVip;

    @BindView(R.id.txt_update)
    TextView txtUpdate;
    @BindView(R.id.tag_cloud)
    TagCloudView tagCloud;

    ValueAnimator valueAnimator;

    private String Path = "https://yxkvideo.youxiake.com/musiclight.mp3";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xiang_qing_da_ting);
        ButterKnife.bind(this);

        UserModel model = Hawk.get(MyConfig.SP_CACHE_USERMODEL);
        isVip = model.is_rut;
        if (isVip) {
        }
        txtUpdate.setVisibility(View.VISIBLE);
        mediaPlayer = new MediaPlayer();
        requestTheAudioFocus();


        tagCloud.setScrollSpeed(10);

//        homeAdapter = new XiangQingAdapter(this, R.layout.item_xiangqing, list);
//        homeAdapter.setVip(isVip);

//        StaggeredGridLayoutManager staggeredGridLayoutManager =
//                new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//        listFriend.setLayoutManager(staggeredGridLayoutManager);
//        listFriend.setAdapter(homeAdapter);
        getLoadDialogAndShow();
        requestData();
//        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//
//                Bundle bundle = new Bundle();
//                bundle.putString("userid", list.get(position).id);
//                goActivity(bundle, PersonHomeActivity.class);
//            }
//        });

//        listFriend.setPullRefreshListener(new PulltoRefreshRecyclerView.RecyPtrHandler() {
//            @Override
//            public void onLoadMore() {
//                requestData();
//            }
//
//            @Override
//            public void onRefresh() {
//
//                listFriend.mCurPager = 1;
//                requestData();
//            }
//        });
        vectorTagsAdapter = new VectorTagsAdapter(this);
        tagCloud.setAdapter(vectorTagsAdapter);


        new Thread(new Runnable() {
            @Override
            public void run() {
                initMediaPlayer(Path);

            }
        }).start();

    }

    Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);


            mediaPlayer.start();
        }
    };


    private void initMediaPlayer(String path) {

        try {
            mediaPlayer.setDataSource(path);//指定音频文件路径
            mediaPlayer.setLooping(true);//设置为循环播放

            mediaPlayer.prepare();//初始化播放器MediaPlayer
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {

                    handler.sendEmptyMessage(1);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    VectorTagsAdapter vectorTagsAdapter;

    public void requestData() {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getXiangqingUserList(mCurPager)
                , new SimpleSubscriber<HttpResult<UserCoustomModel>>() {
                    @Override
                    protected void _onNext(HttpResult<UserCoustomModel> o) {

                        getLoadDialogAndDismiss();

                        UserCoustomModel data = o.getData();
                        if (data != null) {
                            List<UserModel> results = data.results;
//                            if (listFriend.mCurPager == 1) {
//                                list.clear();
//                            }
                            List<UserModel> ss = new ArrayList<>();

                            ss.addAll(results);
                            ss.addAll(results);
                            vectorTagsAdapter.setList(ss);
                            vectorTagsAdapter.notifyDataSetChanged();

//                            list.addAll(results);
//                            homeAdapter.notifyDataSetChanged();
//                            listFriend.refreshComplete();
                            if (data.next == null) {
//                                homeAdapter.loadMoreEnd();

                                mCurPager = 1;
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    @OnClick({R.id.txt_xiangqing, R.id.txt_update})
    public void onViewClicked(View view) {


        switch (view.getId()) {

            case R.id.txt_xiangqing:
                mCurPager ++ ;
                requestData();

                break;

            case R.id.txt_update:

                startActivityForResult(new Intent(this, XiangQingActivity.class), 1);
                break;


        }


    }


    //zxzhong 请求音频焦点 设置监听
    private int requestTheAudioFocus() {
        if (Build.VERSION.SDK_INT < 8) {//Android 2.2开始(API8)才有音频焦点机制
            return 0;
        }
        if (mAudioManager == null) {
            mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        }
        if (mAudioFocusChangeListener == null) {
            mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {//监听器
                @Override
                public void onAudioFocusChange(int focusChange) {
                    switch (focusChange) {
                        case AudioManager.AUDIOFOCUS_GAIN:
                        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
                        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
                            //播放操作
                            break;

                        case AudioManager.AUDIOFOCUS_LOSS:
                        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                            //暂停操作
                            break;
                        default:
                            break;
                    }
                }
            };
        }

//        int requestFocusResult = mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);
        //下面两个常量参数试过很多 都无效，最终反编译了其他app才搞定，汗~
        int requestFocusResult = mAudioManager.requestAudioFocus(mAudioFocusChangeListener,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

        return requestFocusResult;
    }


    /**
     * 用AudioManager获取音频焦点避免音视频声音并发问题
     */
    private AudioManager mAudioManager;
    private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener;


    //zxzhong 暂停、播放完成或退到后台释放音频焦点
    private void releaseTheAudioFocus(AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener) {
        if (mAudioManager != null && mAudioFocusChangeListener != null) {
            mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);
        }
    }


    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onResume() {
        super.onResume();
        requestTheAudioFocus();
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseTheAudioFocus(mAudioFocusChangeListener);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        mediaPlayer.release();
        if (valueAnimator != null) {

            valueAnimator.cancel();
        }

    }


    @Override
    public void onBackPressed() {
        mediaPlayer.release();
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {

            finish();
        }
    }
}
